package edu.ucsur.tp.data;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class MyData {
	
	Connection conexion;
	String error;
	List<Object> ListaValues = new ArrayList<Object>();
	
	public MyData(String host, String usuario, String pw, String base) {

    	try {
	    	Class.forName("com.mysql.jdbc.Driver");
	    	conexion=DriverManager.getConnection("jdbc:mysql://"+host+"/"+base,usuario,pw);
		}
		catch(ClassNotFoundException e){
			error=e.getMessage();	
		}
		catch(SQLException e){
			error=e.getMessage();
		}

     }
	
	public MyData() {

    	try {
	    	Class.forName("com.mysql.jdbc.Driver");
	    	conexion=DriverManager.getConnection("jdbc:mysql://127.0.0.1/db_ccenter","root","peru123");
    	}
		catch(ClassNotFoundException e){
			error=e.getMessage();	
		}
		catch(SQLException e){
			error=e.getMessage();
		}

     }
	
	 public Connection getConexion(){
	    	return conexion;
	 }
	 
	 public void Dispose(){
		 try {
			conexion.close();
		 }
		 catch (Exception ex) {
		 }
	 }
	 
	 
	 public ResultSet GetCursor(String Sql) {
		 ResultSet rs = null;
		 
		 try{
			 Statement stmt = conexion.createStatement();
			 rs = stmt.executeQuery(Sql);
			 
		 }catch (Exception ex){
			 ex.printStackTrace();
		 }
		 
		 return rs;
	 }
	 
	 
	 public void AddValues(Object Valor) {
		 this.ListaValues.add(Valor);
	 }
	 
	
	 public boolean Execute(String Sql, boolean UseListaObj){
		 PreparedStatement psta;
		 
		 if (UseListaObj){
			//Usando PreparedStatement
			try {
				psta = conexion.prepareStatement(Sql);
				for (int i = 0; i < this.ListaValues.size()-1 ; i++) {
					 psta.setObject(i + 1, ListaValues.get(i));
				 }
				 psta.executeUpdate();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
			
			 
		 } else {
			//Usando Statement solamente
			 try {
				Statement stmt = conexion.createStatement();
				stmt.executeUpdate(Sql);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
		 }
		 return true;
	 } 
	 
	 
	 public String getMensajeError(){
	    	return error;
	 }
}
